//
//  HMTabBar.swift
//  Weibo
//
//  Created by 曾成 on 2017/6/4.
//  Copyright © 2017年 WickzZ. All rights reserved.
//

import UIKit

class HMTabBar: UITabBar {
    
    //撰写按钮闭包
    var composeCallBack:(()->())?
    
    //懒加载 自定义按钮
    lazy var composeButton:UIButton = {
        let button = UIButton()
        //添加点击事件
        button.addTarget(self, action:#selector(composeButtonAction) , for: .touchUpInside)
        //设置不同状态下的背景图片
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: .normal)
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), for: .highlighted)
        
        //设置不同状态下的图片
        button.setImage(UIImage(named:"tabbar_compose_icon_add"), for: .normal)
            
        button.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: .highlighted)
        
        button.sizeToFit()
        return button
    }()
    
    //创建视图
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加控件
    private func setupUI(){
    
        addSubview(composeButton)
        backgroundImage = UIImage(named: "tabbar_background")
    }
    
    @objc private func composeButtonAction(){
    
        composeCallBack?()
    }
    
    override func layoutSubviews() {
        //调整子控件之间的位置
        super.layoutSubviews()
        
        //composeButton的中心位置
        composeButton.center.x = width * 0.5
        composeButton.center.y = height * 0.5
        
        //计算每一个的宽度
        let buttonWidth = width / 5
        
        var index = 0
        //遍历每一个按钮
        for subView in self.subviews {
            //UITabBarButton为系统私有
            if subView.isKind(of: NSClassFromString("UITabBarButton")!){
            //记录按钮的宽度
            subView.width = buttonWidth
            //记录按钮的x坐标
            subView.x = CGFloat(index) * buttonWidth
            //记录每次系统按钮的索引
            index += 1
                if index == 2{
                
                    index += 1
                }
            }
        }
    }

}
